//
// Created by v on 18-6-11.
//

#include "cm_conf_ex.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

int cm_config_read_ex(const char *                        file,
                      std::map<std::string, std::string> &data)
{
    FILE *f = NULL;
#ifdef _WIN32
    fopen_s(&f, file, "rb");
#else
    f = fopen(file, "r");
#endif
    if (f)
    {
        char line[128] = {0};
        while (true)
        {
            if (feof(f))
                break;
            char *p = fgets(line, 128, f);
            if (!p)
            {
                break;
            }
            if (line[0] == '\0' || line[0] == '#')
            {
                continue;
            }
            char key[64]    = {0};
            char value[128] = {0};
#ifdef _WIN32
            char *sl     = line;
            char *tosave = key;
            while (true)
            {
                if (*sl == '\0')
                    break;
                if (*sl == '\r' || *sl == '\n')
                {
                    sl++;
                    continue;
                }
                if (*sl == '=')
                {
                    tosave = value;
                    sl++;
                }
                *tosave++ = *sl++;
            }
            int ret = 2;
//          int ret = sscanf_s(line, "%[^=]=%s", key, value);
#else
            int ret = sscanf(line, "%[^=]=%s", key, value);
#endif
            if (ret == 2)
            {
                data.insert(std::make_pair(key, value));
            }
        }
        fclose(f);
    }
    else
    {
        return -2;
    }

    return 0;
}

int cm_config_write_ex(const char *                       file,
                       std::map<std::string, std::string> data)
{
    FILE *f = NULL;
    f       = fopen(file, "w");
    if (!f)
        return -1;

    char line[128] = {0};
    sprintf(line, "%s\n", "# Generated by program.");
    fwrite(line, 1, strlen(line), f);

    for (std::map<std::string, std::string>::iterator iter = data.begin();
         iter != data.end(); iter++)
    {
        std::string key   = iter->first;
        std::string value = iter->second;
        sprintf(line, "%s=%s\n", key.c_str(), value.c_str());
        fwrite(line, 1, strlen(line), f);
    }

    fclose(f);

    return 0;
}